import React, { PureComponent, Fragment } from 'react';
import { Tabs, Row, Typography, Col, Button, Icon, Select, Form, message } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import _ from 'lodash';
import * as utils from '../../utils/treeUtils';
import AuthorizedButton from '@/components/AuthorizedButton';

const { Text } = Typography;
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { Option } = Select;

@connect(state => ({
  searchItems: state.SupplyPlanItems.searchItems,
  all: state.SupplyPlanItems.all,
}))
@Form.create()
export default class PageTop extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      expandForm: false,
      group: '',
      batch: '',
      build: '',
      product: '',
      productType: '',
    };
  }

  componentWillReceiveProps(nextProps) {
    // match变动
    const { setFieldsValue } = this.props.form;
    if (this.props.match.params.version !== nextProps.match.params.version) {
      const { dispatch } = this.props;
      setFieldsValue({ group: '', batch: '', productType: '', product: '', build: '' });
      dispatch({
        type: 'SupplyPlanItems/clear',
      });
      this.setState({
        group: '',
        expandForm: false,
        batch: '',
        build: '',
        product: '',
        productType: '',
      });
    }
  }

  // 根据查询条件搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form, match } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = _.values(
        _.mapValues(fieldsValue, value => (value ? value.split('|')[1] : 'null')),
      ).join('/');
      this.props.getItems(this.props, values);
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      group: '',
      batch: '',
      build: '',
      product: '',
      productType: '',
    });
  };

  // 切换搜索条件的展示方式
  handleScreenBtn = () => {
    const self = this;
    this.setState({
      expandForm: !self.state.expandForm,
    });
    this.props.expandForm(!self.state.expandForm);
  };

  // 搜索条件的展示方式———展开
  renderAdvancedForm = () => {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      style: { marginBottom: 0 },
    };
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { searchItems, all } = this.props;
    const { group, build, product, productType, batch } = this.state;

    // 组团
    let groups = [];
    let batchs = [];
    let products = [];
    let productTypes = [];
    let builds = [];
    // 批次
    batchs = utils.getSearchTypeItems(searchItems.org_batch, 'name', 'id');
    // 组团
    groups = utils.getSearchTypeItems(searchItems.org_group, 'name', 'id');
    // 业态
    products = utils.getSearchTypeItems(searchItems.org_product, 'name', 'id');
    // 产品构成
    productTypes = utils.getSearchTypeItems(
      searchItems.org_product,
      'proProductName',
      'proProductCode',
    );
    // 楼栋
    builds = utils.getSearchTypeItems(searchItems.org_build, 'name', 'id');
    if (batch) {
      // 有组团 取当前组团所有业态产品构成 否 取所有批次下所有业态产品构成
      let orgStage = [];
      orgStage = _.filter(searchItems.org_batch, { id: batch });
      if (!batch && all) {
        orgStage = _.filter(all, { name: orgStage[0].name });
      }
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
      productTypes = utils.getSearchSeltetItems(
        orgStage,
        'org_product',
        'proProductName',
        'proProductCode',
      );
      builds = utils.getSearchSeltetItems(orgStage, 'org_build', 'name', 'id');
    }
    if (group) {
      let orgStage = [];
      orgStage = _.filter(searchItems.org_group, { id: group });
      batchs = utils.getSearchSeltetItems(orgStage, 'org_batch', 'name', 'id');
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
      productTypes = utils.getSearchSeltetItems(
        orgStage,
        'org_product',
        'proProductName',
        'proProductCode',
      );
      builds = utils.getSearchSeltetItems(orgStage, 'org_build', 'name', 'id');
    }

    if (productType) {
      let orgProduct = [];
      let orgBatch = [];
      if (group) {
        const orgGroup = _.filter(searchItems.org_group, { id: group });
        orgProduct = orgGroup[0].children;
      } else if (batch) {
        orgBatch = _.filter(searchItems.org_batch, { id: batch });
        const allGroup = [];
        orgProduct = utils.buildChildren(allGroup, orgBatch, 'org_product');
      } else {
        orgProduct = searchItems.org_product;
      }
      orgBatch = _.filter(orgProduct, { proProductCode: productType });
      products = utils.getSearchSeltetItems(orgBatch, 'org_product', 'name', 'id');
      builds = utils.getSearchSeltetItems(orgBatch, 'org_build', 'name', 'id');
    }
    if (product) {
      let orgProduct = [];
      let orgBatch = [];
      if (group) {
        const orgGroup = _.filter(searchItems.org_group, { id: group });
        orgProduct = orgGroup[0].children;
      } else if (batch) {
        orgBatch = _.filter(searchItems.org_stage, { id: batch });
        const allGroup = [];
        orgProduct = utils.buildChildren(allGroup, orgBatch, 'org_product');
      } else {
        orgProduct = searchItems.org_product;
      }
      if (group === '' && batch === '') {
        const productName = _.filter(searchItems.org_product, { id: product });
        orgProduct = _.filter(searchItems.org_product, { name: productName[0].name });
      } else {
        orgProduct = _.filter(orgProduct, { id: product });
      }
      builds = utils.getSearchSeltetItems(orgProduct, 'org_build', 'name', 'id');
    }

    return (
      <Form onSubmit={this.handleSearch} layout="horizontal">
        <Row type="flex" justify="space-around" align="middle">
          <Col md={20} sm={24}>
            <Row>
              <Col md={6} sm={24}>
                <FormItem {...formItemLayout} label="组团">
                  {getFieldDecorator(
                    'group',
                    {},
                  )(
                    <Select
                      size="small"
                      placeholder="全部"
                      onChange={value => {
                        setFieldsValue({ batch: '', productType: '', product: '', build: '' });
                        this.setState({
                          group: value.split('|')[0],
                          batch: '',
                          productType: '',
                          product: '',
                          build: '',
                        });
                      }}
                    >
                      <Option value="">全部</Option>
                      {groups &&
                        groups.length > 0 &&
                        groups.map(value => (
                          <Option key={value.code} value={`${value.code}|${value.name}`}>
                            {value.name || '暂无名称'}
                          </Option>
                        ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>

              {batchs.length ? (
                <Col md={6} sm={24}>
                  <FormItem {...formItemLayout} label="批次">
                    {getFieldDecorator(
                      'batch',
                      {},
                    )(
                      <Select
                        onChange={value => {
                          setFieldsValue({ productType: '', product: '', build: '' });
                          this.setState({
                            batch: value.split('|')[0],
                            productType: '',
                            product: '',
                            build: '',
                          });
                        }}
                        size="small"
                        placeholder="全部"
                      >
                        <Option value="">全部</Option>
                        {batchs &&
                          batchs.length > 0 &&
                          batchs.map(value => (
                            <Option key={value.code} value={`${value.code}|${value.name}`}>
                              {value.name || '暂无名称'}
                            </Option>
                          ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
              ) : null}
              <Col md={6} sm={24}>
                <FormItem {...formItemLayout} label="业态">
                  {getFieldDecorator(
                    'productType',
                    {},
                  )(
                    <Select
                      size="small"
                      onChange={value => {
                        setFieldsValue({ build: '', product: '' });
                        this.setState({
                          productType: value.split('|')[0],
                          product: '',
                          build: '',
                        });
                      }}
                      placeholder="全部"
                    >
                      <Option value="">全部</Option>
                      {productTypes &&
                        productTypes.length > 0 &&
                        productTypes.map(value => (
                          <Option key={value.code} value={`${value.code}|${value.name}`}>
                            {value.name || '暂无名称'}
                          </Option>
                        ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>
              <Col md={6} sm={24}>
                <FormItem {...formItemLayout} label="产品构成">
                  {getFieldDecorator(
                    'product',
                    {},
                  )(
                    <Select
                      size="small"
                      onChange={value => {
                        setFieldsValue({ build: '' });
                        this.setState({
                          product: value.split('|')[0],
                          build: '',
                        });
                      }}
                      placeholder="全部"
                    >
                      <Option value="">全部</Option>
                      {products &&
                        products.length > 0 &&
                        products.map(value => (
                          <Option key={value.code} value={`${value.code}|${value.name}`}>
                            {value.name || '暂无名称'}
                          </Option>
                        ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>
              {builds.length ? (
                <Col md={6} sm={24}>
                  <FormItem {...formItemLayout} label="楼栋">
                    {getFieldDecorator(
                      'build',
                      {},
                    )(
                      <Select
                        onChange={value => {
                          this.setState({
                            build: value.split('|')[0],
                          });
                        }}
                        size="small"
                        placeholder="全部"
                      >
                        <Option value="">全部</Option>
                        {builds &&
                          builds.length > 0 &&
                          builds.map(value => (
                            <Option key={value.code} value={`${value.code}|${value.name}`}>
                              {value.name || '暂无名称'}
                            </Option>
                          ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
              ) : null}
            </Row>
          </Col>
          <Col md={4} sm={24} justify="space-around" align="middle">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  // 选择搜索条件的展示方式
  renderForm = () => (this.state.expandForm ? this.renderAdvancedForm() : null);

  // nav 切换改变状态
  handleTabChange = (key, params) => {
    router.push(
      `/OperatingPlan/SupplyPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${key}`,
    );
    this.setState({
      expandForm: false,
    });
  };

  render() {
    const { params } = this.props.match;
    const activeKey = params.category;
    const { versions } = this.props;
    let currentState = [];
    if (versions.length > 0 && params.version) {
      currentState = _.filter(versions, { versionId: params.version });
    }
    return (
      <Fragment>
        <Fragment>
          <div className="header-categories">
            <Tabs
              activeKey={activeKey}
              animated={false}
              size="large"
              onChange={key => this.handleTabChange(key, params)}
              tabBarExtraContent={
                <>
                  {params.category === 'budget' ? (
                    <AuthorizedButton authority={`supply_${params.category}_addVersion`}>
                      <Button
                        style={{ marginRight: '5px' }}
                        type="primary"
                        onClick={() => this.props.handleCreateEdition(params.stage)}
                      >
                        创建新版本
                      </Button>
                    </AuthorizedButton>
                  ) : null}
                  {versions && versions.length ? (
                    <Button onClick={this.handleScreenBtn}>
                      高级筛选
                      {this.state.expandForm ? <Icon type="up" /> : <Icon type="down" />}
                    </Button>
                  ) : null}
                </>
              }
            >
              <TabPane tab="月度动态版" key="dynamic"></TabPane>
              <TabPane tab="预算版" key="budget"></TabPane>
              <TabPane tab="战规版" key="strategy"></TabPane>
              <TabPane tab="投资版" key="investment"></TabPane>
            </Tabs>
          </div>
        </Fragment>

        <div className="header-search-area">{this.renderForm()}</div>
        {versions.length && currentState.length ? (
          <>
            <Row
              className="header-version-area header-version-edit-area"
              type="flex"
              justify="space-around"
              align="middle"
            >
              <Col md={4} className="version-selecter" sm={24}>
                <Select
                  onChange={value => {
                    router.replace(
                      `/OperatingPlan/SupplyPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${value}`,
                    );
                  }}
                  size="small"
                  className="version-select"
                  value={currentState[0].versionId}
                >
                  {versions.map(val => (
                    <Option key={val.versionId} value={val.versionId}>
                      {val.versionName}
                    </Option>
                  ))}
                </Select>
              </Col>
              <Col className="version-details" md={20} sm={24}>
                {currentState[0].priceVersionName ? (
                  <Text>（{`基于货值版本：${currentState[0].priceVersionName}`}</Text>
                ) : null}
                {currentState[0].buildplanVersionName ? (
                  <Text>，{`楼栋计划版本：${currentState[0].buildplanVersionName}`}）</Text>
                ) : null}
              </Col>
            </Row>
          </>
        ) : null}
      </Fragment>
    );
  }
}
